import axios from "axios";
import router from '../router'
import {showErrorMsg,  showWarningMsg} from "../utils/msg";



axios.defaults.timeout = 100000;
axios.defaults.baseURL = "/api";


function getToken(){
    let token
    try {
        token = localStorage.getItem('token')
    } catch (error) {
        return ''
    }
    return token
}


function getUser(){
    let username
    try {
        username = localStorage.getItem('username')
    } catch (error) {
        username = ''
    }
    return username
}


/**
 * http request 拦截器
 */
axios.interceptors.request.use(
    (config) => {
        config.data = JSON.stringify(config.data);
        config.headers = {
            "Content-Type": "application/json",
            'token': getToken(),
            'username': getUser()
        };
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);


//统一接口处理，返回数据
export function request (fetch, url, param) {
    return new Promise((resolve, reject) => {
        switch (fetch) {
            case "get":
                console.log("begin a get request,and url:", url);
                axios.get(url, {params: param})
                    .then((response) => {
                        if (response.status === 200) {
                            if (response.data.code === 503) {
                                showWarningMsg(response.data.msg)
                                router.push('/login')
                            }
                            resolve(response.data);
                        } else {
                            showWarningMsg("code:" + response.status);
                        }
                    })
                    .catch((error) => {
                        showErrorMsg(error.toString())
                        reject(error);
                    });
                break;

            case "post":
                axios.post(url, param)
                    .then((response) =>{
                        if (response.status === 200) {
                            if (response.data.code === 503) {
                                showWarningMsg(response.data.msg)
                                router.push('/login')
                            }
                            resolve(response.data);
                        } else {
                            showWarningMsg("code: " + response.status)
                        }
                        resolve(response.data);
                    })
                    .catch((error) => {
                        showErrorMsg(error.toString())
                        reject(error);
                    });
                break;
            default:
                break;
        }
    });
}
